//
//  HMWBUserInfoViewModel.swift
//  Weibo
//
//  Created by 李学林 on 15/12/8.
//  Copyright © 2015年 tete. All rights reserved.
//

import UIKit

class HMWBUserInfoViewModel{
    
    var userAccount: HMWBUserInfo?
    // 是否登录
    var userLogin: Bool{
        return accessToken != nil
    }
    
    var accessToken: String? {
        if let accessToken = userAccount?.access_token where !isExpires {
            // 判断是否过期
            return accessToken
        }
        return nil
    }
    
    var isExpires: Bool{
    
        guard let expiresDate = userAccount?.expiresDate else {
            return true
        }
        // 测试用的  
//        let newDate = expiresDate.dateByAddingTimeInterval(0)
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending{
        
            return false
        }
        return true
    }
    
    
    // 全局访问点
    static let sharedAccount :HMWBUserInfoViewModel = HMWBUserInfoViewModel();
    // 构造方法私有化
    private init(){
        // 从本地存好的归档中提取数据
        userAccount = loaduserAccount()
    }
    
}
// oAuth网络请求
extension HMWBUserInfoViewModel{

    // 请求获得 AceessToken
    func getAccessToken(code:String, complete:(isSuccess: Bool)->()){
        
        NetworkTools.shareManager.loadAccessToken(code) { (response, error) -> () in
            
            if error != nil {
                printLog("\(error)")
                complete(isSuccess: false)
                
                return
            }
            // 在强转的时候,`!` 与 `?` 怎么选,只要看前面的数据是否是一个可选值
            guard let dict = response as? [String: AnyObject] else {
                printLog("返回数据不是字典")
                return
            }
            
            let account = HMWBUserInfo(dict: dict)
            printLog(account)
            
            // 封装添加的
            self.userAccount = account
            
            self.loadUserInfo(account.uid!, access_token: account.access_token!,complete: complete)
//            complete(isSuccess: true)
            
          }
        
    }

    private func loadUserInfo(uid: String, access_token: String, complete:(isSuccess: Bool)->()){
        
        NetworkTools.shareManager.loadUserInfo(uid, access_token: access_token) { (response, error) -> () in
            
            //  根据account_token请求用户的数据
            if error != nil{
                printLog("请求错误")
                complete(isSuccess: false)
                return
            }
            printLog(response)
            
            guard let responseDic = response as? [String: AnyObject] else{
                printLog("返回数据不是一个字典")
                return
            }
            
            // 给新的模型属性赋值
            self.userAccount?.avatar_large = responseDic["avatar_large"] as? String
            self.userAccount?.screen_name = responseDic["screen_name"] as? String
            
            
            // 将用户数据存储到本地
            self.saveAccountInfo(self.userAccount!)
            
            complete(isSuccess: true)

        }
        
    }

}

// MARK: - 归档和解档
extension HMWBUserInfoViewModel{

    // 存储当前对象
    func saveAccountInfo(mod: HMWBUserInfo){
        // 获取路径
        let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
        printLog(file)
        
        // 归档
        NSKeyedArchiver.archiveRootObject(mod, toFile: file)
        
    }
    
    func loaduserAccount() -> HMWBUserInfo? {
        // 1. 获取路径
        let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
        // 2. 解档
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? HMWBUserInfo
        return result
    }
    


}